import os
from utils import process_admin, process_shop_order, process_admin_order, process_rider_order
from flask import Flask, render_template, request, send_from_directory

app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
DATABASE_FOLDER = 'database'
app.config['DATABASE_FOLDER'] = DATABASE_FOLDER
os.makedirs(DATABASE_FOLDER, exist_ok=True)
DATABASE_INDEX = os.path.join(app.config['DATABASE_FOLDER'], 'index.txt')
app.config['DATABASE_INDEX'] = DATABASE_INDEX
if not os.path.exists(DATABASE_INDEX):
    with open(DATABASE_INDEX, 'w', encoding='utf-8') as index_file:
        pass

@app.route('/', methods=['GET', 'POST'])
def index():

    message = '' # 初始化 message 变量
    highlighted_entry = None # 初始化 highlighted_entry 变量

    if request.method == 'POST':
        file = request.files['file']
        if file:
            filename = file.filename
            filename_without_extension = os.path.splitext(filename)[0]

            # 检查是否已经存在相同的文件名
            if filename_without_extension in [line.strip() for line in open(DATABASE_INDEX, 'r', encoding='utf-8').readlines()]:
                message = '文件已存在，上传失败！'
                highlighted_entry = filename_without_extension # 高亮已存在的条目
            else:
                filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
                file.save(filepath)

                # 使用原输入文件名作为唯一文件夹名
                new_folder_path = os.path.join(app.config['DATABASE_FOLDER'], filename_without_extension)
                os.makedirs(new_folder_path, exist_ok=True)

                # 更新索引文件
                with open(DATABASE_INDEX, 'a', encoding='utf-8') as index_file:
                    index_file.write(f'{filename_without_extension}\n')

                # 处理文件
                admin_file = process_admin(filepath, new_folder_path)
                process_shop_order(admin_file, new_folder_path)
                process_admin_order(admin_file, new_folder_path)
                process_rider_order(admin_file, new_folder_path)

                message = '文件处理完成！'
                highlighted_entry = filename_without_extension # 高亮新上传的条目
    else:
        message = '请上传文件'

    database_entries = []
    if os.path.exists(DATABASE_INDEX):
        with open(DATABASE_INDEX, 'r', encoding='utf-8') as index_file:
            database_entries = [line.strip() for line in index_file]

    return render_template('index.html', message=message, 
                           database_entries=database_entries,
                           highlighted_entry=highlighted_entry) # 传递 highlighted_entry


@app.route('/orders/<folder_name>')
def show_orders(folder_name):
    new_folder_path = os.path.join(app.config['DATABASE_FOLDER'], folder_name)
    
    if not os.path.exists(new_folder_path):
        return "No such database entry", 404

    time_slots = []
    orders = {
        'shop': {},
        'admin': {},
        'rider': {}
    }

    for folder in ['shop_orders', 'admin_orders', 'rider_orders']:
        folder_path = os.path.join(new_folder_path, folder)
        if not os.path.exists(folder_path):
            continue

        for filename in os.listdir(folder_path):
            if filename.endswith(".txt"):
                with open(os.path.join(folder_path, filename), 'r', encoding='utf-8-sig') as f:
                    time_slot = filename.split('_')[0]
                    time_slots.append(time_slot)
                    orders[folder.split('_')[0]][time_slot] = f.read()

    time_slots = sorted(list(set(time_slots)))
    # 修改：从 URL 参数中获取 selected_time_slot
    selected_time_slot = request.args.get('time_slot') 
    # 如果 URL 参数中没有提供 time_slot，才使用默认值
    if selected_time_slot not in time_slots and time_slots:
        selected_time_slot = time_slots[0]
    # 获取 static/images 目录下的所有图片文件名
    image_files = [
        f for f in os.listdir(os.path.join(app.static_folder, 'images')) 
        if os.path.join(app.static_folder, 'images', f).endswith(('.jpg', '.jpeg', '.png', '.JPG', '.JPEG', '.PNG'))
    ]

    return render_template('orders.html', 
                           time_slots=time_slots, 
                           orders=orders, 
                           selected_time_slot=selected_time_slot, 
                           folder_name=folder_name,
                           image_files=image_files)  # 传递图片文件名列表


@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

if __name__ == '__main__':
    app.run(debug=True)